package us.fourdesign.zptjob.util;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.widget.ImageView;

public class AsyncImageLoader extends AsyncTask<Object, Integer, Bitmap> {

	private static Context mContext = null;
	private SoftReference<ImageView> imageView = null;
	private String tag;
	boolean isZoom = false;
	boolean isBig = false;
	int screenWidth;

	public static synchronized void AsyncImageDownLoadHelper(Object... params) {
		new AsyncImageLoader().execute(params);
	}

//	public static Bitmap loadImageFromCache(String key) {
//		return WeiboInstance.readImageFromSD(key);
//	}

	private Bitmap loadImageFromUrl(String urlString) {
		Bitmap imageBitmap = null;
		try {
			URL url = new URL(urlString);
			imageBitmap = BitmapFactory.decodeStream(url.openStream());
		} catch (MalformedURLException e1) {
			return null;
		} catch (IOException e) {
			return null;
		}
		return imageBitmap;
	}

//	private Bitmap FixImage(Bitmap image, boolean zoom, boolean big) {
//		StoreImageType type = StoreImageType.ICON;
//		if (zoom || big) {
//			type = StoreImageType.THUMBNAIL;
//			Matrix matrix = new Matrix();
//			int orgWidth = image.getWidth();
//			int orgHeight = image.getHeight();
//			if (zoom) {
//				float scalewidth = (float) WeiboHelper.dip2px(mContext, 120) / orgWidth;
//				float scaleHeight = (float) WeiboHelper.dip2px(mContext, 120) / orgHeight;
//				float scale = Math.min(scalewidth, scaleHeight);
//				matrix.postScale(scale, scale);
//			} else if (big) {
//				float scale = (float) screenWidth / orgWidth;
//				matrix.postScale(scale, scale);
//			}
//			image = Bitmap.createBitmap(image, 0, 0, orgWidth, orgHeight, matrix, true);
//		}
//		WeiboInstance.storeImageToSD(tag, image, type);
//		return image;
//	}

	@Override
	protected void onPostExecute(Bitmap image) {
		if (image != null) {
//			image = FixImage(image, isZoom, isBig);
			imageView.get().setImageBitmap(image);
		}
	}

	@Override
	protected Bitmap doInBackground(Object... params) {
		// TODO Auto-generated method stub
		isZoom = false;
		isBig = false;
		imageView = new SoftReference<ImageView>((ImageView) params[1]);
		tag = params[0].toString();
		Bitmap image = null;
		if (params.length >= 3) {
			if (mContext == null)
				mContext = (Context) params[3];
			if (params[2].toString() == "zoom") {
				isZoom = true;
			} else if (params[2].toString() == "big") {
				isZoom = false;
				isBig = true;
				screenWidth = Integer.parseInt(params[4].toString());
			}
		}
		image = loadImageFromUrl(tag);
		return image;
	}
}